<?php

namespace app\api\controller;

use app\api\controller\Tpmecms;
use think\Db;
use think\Config;

/**
 * 匹配💖💖
 */
class Match extends Tpmecms
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['test'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * 探索
     * 
     * @param string $match_sex 性别:1=男,2=女(可不传)0随机
     * @param string $match_school 1=本校，2=全部
     * @param string $character_ids 个性标签
     * @return void
     */
    public function new_match($match_sex=null,$match_school=null,$character_ids=null)
    {

        $where_com['match_switch'] = 1;//匹配开关
        $where_com['id'] = ['<>',$this->auth->id];
        if(empty($character_ids)){
            //随机匹配
            // $this->New_match();
            $character_ids = $this->auth->match_ids;
        }else{
            $user_up['match_ids'] = $character_ids;

        }
        //性别
        if(!$match_sex){
           $sex = $this->auth->match_sex;
        }else{
            $sex = $match_sex;
            $user_up['match_sex'] = $sex;
        }
        // else{
        //     //查询设置里面的匹配
        //     $this->New_match($this->auth->match_ids);
        // }

        //用户今天是否可以匹配
        $this->UserTodayIsMatch($this->auth->id);
        $where = null;

        
        if($sex == '1' || $sex == '2')
            $where_com['sex'] = $sex;

        if($match_school){
            
            $school_id = $match_school;
            $user_up['match_school'] = $match_school;
        }else{
            $school_id = $this->auth->match_school;
        }
        if(isset($user_up)){
            Db::name('user')->where('id',$this->auth->id)->update($user_up);
        }

        switch ($school_id) {
            case '1':
                $where['school_id'] = $this->auth->school_id;
                break;
            case '2':
                
                break;
            default:
                # code...
                break;
        }

        
        $user_ids = false;
        if($character_ids){
            $character_arr = explode(',',$character_ids);
            
            foreach ($character_arr as $key => $character_id) {
                unset($where2);
                $where2[] = ['exp',db::raw("find_in_set('$character_id',character_ids)")];
                $temp_ids = Db::name('user')->where($where2)->column('id');
                
                if(sizeof($temp_ids)>0 && $user_ids){
                  
                    $t =  array_intersect($temp_ids,$user_ids);
                    if($t){
                        // halt('$t');
                        $user_ids = $t;
                    
                    }

                }else{
                    if(!$user_ids)
                    $user_ids = $temp_ids;
                    
                }
            }
         
            if($user_ids){
                $where['id'] = ['in',$user_ids];
            }
            // array_intersect()
            // $where[] = ['exp',db::raw("find_in_set('$character_ids',character_ids)")];
        }
        
        
        
        //不参与匹配的用户ids
        
        $not_user_ids = $this->GetUserMatchUserIds($this->auth->id);
        if($not_user_ids)
            $where_com['id'] = ['not in',$not_user_ids];

        
        $user = Db::name('user')->where($where_com)->where($where)->order('createtime desc')->field($this->GetMatchUserField())->find();
        if(!$user){

            $user = Db::name('user')
                    ->where($where_com)
                    ->where(function($w){
                        $w->where('rand()');
                    })
                    // ->orderRaw('rand()')
                    ->field($this->GetMatchUserField())
                    ->find();

                    // $this->error($user['id'],$where_com);
            if(!$user){
                $this->error('未匹配',['where'=>$where,'com'=>$where_com]);
            }
        }

        if($user){
          
            if($character_ids){
                $user['character_ratio'] = round(sizeof($this->CharacterSimilar($user['character_ids'],$this->auth->character_ids))/sizeof($character_arr)*100,2);
            
            }
            $user['similar'] = $this->GetCharacterIdsArray($this->CharacterSimilar($user['character_ids'],$this->auth->character_ids));
            $user['school'] = Db::name('school')->where('id',$user['school_id'])->value('name');
            $user['character'] = $this->GetCharacterIdsArray($user['character_ids']);

            //插入用户的匹配记录
            $this->IncMatchLog($this->auth->id,$user['id'],$character_ids,$user['character_ids']);
        }

        

        
        $this->success('ok', $user);
    }


    /**
     * 获取今日已匹配的用户列表
     *
     * @return void
     */
    public function get_today_list()
    {
        $user_ids = Db::name('match')->where('uid',$this->auth->id)->where('date',date('Y-m-d'))->column('user_id');
        if($user_ids){
            $list = Db::name('user')->where('id','in',$user_ids)->field($this->GetMatchUserField())->select();
            foreach ($list as $key => &$user) {
                $user['school'] = Db::name('school')->where('id',$user['school_id'])->value('name');
                $user['character'] = $this->GetCharacterIdsArray($user['character_ids']);
            }
            $this->success('ok', $list);
        }else{
            $this->error('今日未匹配哦');
        }
    }

    /**
     * 获取今日剩余匹配次数
     *
     * @return void
     */
    public function get_today_surplus_num()
    {

        $num = $this->GetUserTodayMatchNum($this->auth->id);//Db::name('match')->where($data)->count();
        $match_num = Config::get('site.everyday_match_num');

        // if($num >= $match_num){
        //     $this->error('今日次数已用完');
        // }
        $this->success('ok', $match_num-$num);
        // $count = Db::name('match')->where('uid',$this->auth->id)->where('date',date('Y-m-d'))->count();
        // if($user_ids){
        //     $list = Db::name('user')->where('id','in',$user_ids)->field($this->GetMatchUserField())->select();
        //     foreach ($list as $key => &$user) {
        //         $user['school'] = Db::name('school')->where('id',$user['school_id'])->value('name');
        //         $user['character'] = $this->GetCharacterIdsArray($user['character_ids']);
        //     }
        //     $this->success('ok', $list);
        // }else{
        //     $this->error('今日未匹配哦');
        // }
    }


    /**
     * 获取匹配用户字段
     *
     * @return void
     */
    protected function GetMatchUserField(){
        return 'id,nickname,avatar,school_id,character_ids,sex';
    }

    /**
     * 个性相似
     *
     * @param string $ids 个性id
     * @param string $ids2 个性id
     * @return void
     */
    protected function CharacterSimilar($ids,$ids2=null)
    { 
        $ids_arr = explode(',',$ids);
        $ids2_arr = explode(',',$ids2);
        if(!$ids2){
            
            return $ids_arr;
        }
        $t =  array_intersect($ids_arr,$ids2_arr);
        
        return $t;
    }

    protected function GetUserMatchUserIds($uid)
    {
        if(!Config::get('site.repeat_match_switch')){
            $data['uid'] = $uid;

            $ids = Db::name('match')->distinct(true)->field('user_id')->where($data)->column('user_id');
            // $this->error(implode(',',$ids),$ids);
            if($ids)
                // return implode(',',array_push($ids,$uid));
                return implode(',',$ids);
        }
    
        return false;
    }

    // protected function IncMatch($uid)
    // {
    //     $data['uid'] = $this->auth->id;
    //     $data['user_id'] = $uid;
    //     $data['time'] = time();
    //     $data['date'] = date('Y-m-d');
    //     Db::name('match')->insert($data);
    //     // if($ids){
    //     //     $where[] = ['exp',db::raw("find_in_set('$id',category)")];
    //     //     $list = Db::name('user')->where('character_ids',$this->auth->id)->order('time desc')->find();
    //     // }
        
    // }

    // /**
    //  * 获取所有的动态空间列表
    //  *
    //  * @param integer $school_id 学校ID(可不传)
    //  * @param integer $page 1
    //  * @param integer $limit 10
    //  * @return void
    //  */
    // public function get_zone_list($school_id=null,$page=1,$limit=10)
    // {
    //     $where = null;
    //     if($school_id)
    //     $where['school_id'] = $school_id;

    //     $list = Db::name('zone')->where($where)->order('time desc')->select();
    //     if($list){
    //         foreach ($list as $key => &$val) {
    //             $val = $this->ChangeFieldZoneListData($val);
    //         }
    //     }
    //     $this->success('ok', $list);
    // }

    // /**
    //  * 获取用户的动态空间列表
    //  *
    //  * @param integer $uid 用户ID
    //  * @param integer $page 1
    //  * @param integer $limit 10
    //  * @return void
    //  */
    // public function get_user_zone_list($uid,$page=1,$limit=10)
    // {
    //     $list = Db::name('zone')->where('uid',$uid)->order('time desc')->select();
    //     if($list){
    //         foreach ($list as $key => &$val) {
    //             $val = $this->ChangeFieldZoneListData($val);
    //         }
    //     }
    //     $this->success('ok', $list);
    // }

    // /**
    //  * 获取动态详情
    //  *
    //  * @param int $id 动态ID
    //  * @return void
    //  */
    // public function get_data($id)
    // {
    //     $val = Db::name('zone')->where('id',$id)->find();
    //     if($val){
    //         $val = $this->ChangeFieldZoneData($val);
    //     }else{
    //         $this->error('该动态不存在');
    //     }
    //     $this->IncZoneViews($id);
    //     $this->success('ok', $val);

    // }


    // /**
    //  * 改变空间字段
    //  *
    //  * @param array $val 
    //  * @return void
    //  */
    // protected function ChangeFieldZoneListData($val){
    //     // $val['comment'] = $this->GetZoneCommentArray($val['id']);//获取空间评论列表
    //     $val['user'] = $this->GetUserData2($val['uid']);
    //     $val['m'] = date('n',$val['time']);
    //     $val['d'] = date('d',$val['time']);
    //     $val['comment_num'] = $this->GetZoneCommentNum($val['id']);
    //     $val['self_likes'] = $this->GetUserIsZonelikes($val['id'],$this->auth->id);
    //     return $val;
    // }



    //  /**
    //  * 改变空间字段
    //  *
    //  * @param array $val 
    //  * @return void
    //  */
    // protected function ChangeFieldZoneData($val){
    //     $val['comment'] = $this->GetZoneCommentArray($val['id']);//获取空间评论列表
    //     $val['m'] = date('n',$val['time']);
    //     $val['d'] = date('d',$val['time']);
    //     $val['comment_num'] = $this->GetZoneCommentNum($val['id']);
    //     $val['self_likes'] = $this->GetUserIsZonelikes($val['id'],$this->auth->id);
    //     $val['date_str'] = $this->TimeToStr($val['time']);
    //     return $val;
    // }

    // /**
    //  * 评论动态
    //  *
    //  * @param int $zone_id 动态id
    //  * @param string $content 内容
    //  * @param string $images 图集(可不传)
    //  * @param int $comment_id 评论id(可不传)
    //  * @return void
    //  */
    // public function add_comment($zone_id,$content=null,$comment_id=null,$images=null)
    // {
    //     $val = Db::name('zone')->where('id',$zone_id)->find();
    //     if(!$val){
    //         $this->error('该动态不存在');
    //     }
    //     $where['zone_id'] = $zone_id;
    //     if($comment_id){

    //         $res = Db::name('zone_comment')->where('id',$comment_id)->where($where)->find();
    //         if(!$res){
    //             $this->error('该评论不存在');
    //         }
    //     }
    //     $where['comment_id'] = $comment_id;
    //     $where['content'] = $content;
    //     $where['images'] = $images;
    //     $where['uid'] = $this->auth->id;
    //     $where['time'] = time();     

    //     $id = Db::name('zone_comment')->insertGetId($where);
    //     $this->success('评论成功', $id);
    // }


    
    // /**
    //  * 修改点赞
    //  *
    //  * @param int $zone_id 动态id
    //  * @return void
    //  */
    // public function update_likes($zone_id)
    // {

    //     $data['uid'] = $this->auth->id;
    //     $data['zone_id'] = $zone_id;
    //     $zone = Db::name('zone')->where('id',$zone_id)->find();
    //     $res = Db::name('zonelikes')->where($data)->find();
    //     if(!$res){
    //         $data['time'] = time();
    //         if(!$zone)$this->error('该动态不存在');
    //         // $data['zone_uid'] = $zone['uid'];
    //         $data['id'] = Db::name('zonelikes')->insertGetId($data);
    //         //点赞数+1
    //         $this->IncZoneLikes($zone_id);
    //         $this->success('点赞成功',1);
    //     }else{
    //         Db::name('zonelikes')->where('id',$res['id'])->delete();
    //         //点赞数-1
    //         $this->DecZoneLikes($zone_id);
    //         $this->success('取消点赞',0);
    //     }
    // }



}
